package communication;

import java.util.concurrent.*;

/**
 * @author 李泽伟
 */
public class Main {
    public static void main(String[] args) {
//        Communication communication = new Communication();
//        Thread t1 = new Thread(communication);
//        Thread t2 = new Thread(communication);
//        t1.setName("线程1");
//        t2.setName("线程2");
//        t1.start();
//        t2.start();
        ExecutorService service = Executors.newFixedThreadPool(10);
        System.out.println(service.getClass());
        ThreadPoolExecutor service1 = (ThreadPoolExecutor) service;
        service1.setCorePoolSize(20);
        // execute适合于Runnable接口
        service.execute(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 100; i++) {
                    System.out.println(Thread.currentThread().getName()+":"+i);
                }
            }
        });
        //submit适合于Callable接口的线程
        service.submit(new Callable<Object>() {
            @Override
            public Object call() throws Exception {
                for (int i = 0; i < 100; i++) {
                    System.out.println(Thread.currentThread().getName()+":"+i);
                }
                return null;
            }
        });
    }
}

class Communication implements Runnable{
    /**
     * 两个线程通信，交替打印1~100的数字
     */
    private int num = 1;
    @Override
    public void run() {
        while (true){
            synchronized (this){
                //wait、notify、notifyAll必须使用在同步代码块或者同步方法中
                //wait、notify、notifyAll的调用者必须是同步代码块中的同步监视器
                //wait、notify、notifyAll是定义在Java.lang.Object中的
                // notify()， notifyAll()会把阻塞的线程唤醒，notify只能唤醒1个被wait的线程
                notifyAll();
                if (num<100){
                    System.out.println(Thread.currentThread().getName()+":"+num);
                    num++;
                    //使得调用如下wait方法的线程进入阻塞状态,wait会自动释放锁
                    try {
                        wait();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }else {
                    break;
                }
            }
        }
    }
}